class Response(object):
    """ 用于封装用户请求的响应信息 """

    def __init__(self, response, request):
        self._response = response
        self.url = response.url
        self.status = response.status
        self.headers = response.headers
        self.request = request
        self.cookies = response.cookies
        self._encoding = request.encoding

    @property
    def selector(self):
        from parsel import Selector
        if self._cached_selector is None:
            self._cached_selector = Selector(self.text)
        return self._cached_selector

    def xpath(self, query, **kwargs):
        return self.selector.xpath(query, **kwargs)

    def css(self, query):
        return self.selector.css(query)

    @property
    def read(self):
        return self._response.read()

    @property
    def json(self):
        return self._response.json()

    @property
    def text(self):
        if self._encoding:
            return self._response.text(self._encoding)
        else:
            self._response.text()
